package de.homelabs.spring.freemarker.service;

import java.util.List;

import de.homelabs.spring.freemarker.domain.HLTemplateElement;
import de.homelabs.spring.freemarker.domain.TemplateContainer;

/**
 * 
 * @author D.Mueller
 *
 * singleton
 */
public class HLFreeMarkerTemplateManager implements IFreeMarkerTemplateManager {
	//Singeltion Design Pattern
	private static HLFreeMarkerTemplateManager instance = new HLFreeMarkerTemplateManager();
	
	//Vars
	private List<TemplateContainer> containerList;
	private TemplateContainer defaultContainer;
	
	private List<HLTemplateElement> templateList;
	
	/**
	 * private constructor
	 */
	private HLFreeMarkerTemplateManager(){}
	
	/**
	 * singelton function
	 */
	public static HLFreeMarkerTemplateManager getInstance(){
		return instance;
	}
	
	@Override
	public TemplateContainer getTemplateContainerByTemplateKey(String templateKey) {
		//containerlist empty?
		if (containerList == null || containerList.isEmpty())
			return this.defaultContainer;
		
		//search for container with key
		for (TemplateContainer container : containerList) {
			if (container.getContainerKey().equalsIgnoreCase(templateKey))
				//container found
				return container;
		}
		
		//if no container found, return default
		return this.defaultContainer;
	}

	@Override
	public boolean setTemplateContainerList(
			List<TemplateContainer> containerList) {
		this.containerList = containerList;
		return true;
	}

	@Override
	public List<TemplateContainer> getTemplateContainerList() {
		return this.containerList;
	}

	@Override
	public TemplateContainer getDefaultTemplateContainer() {
		return this.defaultContainer;
	}

	@Override
	public boolean setDefaultTemplateContainer(TemplateContainer container) {
		this.defaultContainer = container;
		return true;
	}

	public List<HLTemplateElement> getTemplateList() {
		return templateList;
	}

	public void setTemplateList(List<HLTemplateElement> templateList) {
		this.templateList = templateList;
	}
	
	public HLTemplateElement findTemplate(String templateKey){
		for (HLTemplateElement el : this.templateList){
			if (el.getTemplateKey().equals(templateKey)){
				return el;
			}
		} 
		
		return null;
	}
}
